package com.dage.salesflow.shardingjdbc;

import com.alibaba.excel.util.ListUtils;
import com.jfinal.plugin.activerecord.DbKit;
import io.jboot.utils.ReflectUtil;
import org.apache.shardingsphere.core.rule.TableRule;
import org.apache.shardingsphere.shardingjdbc.jdbc.core.datasource.ShardingDataSource;
import org.apache.shardingsphere.underlying.common.rule.DataNode;

import java.util.Collection;
import java.util.List;
import java.util.Set;

public class ShardingJdbcConfig {
	/**
	 * 动态添加分表数据
	 *
	 * @param logicTable      逻辑表名
	 * @param actualTableNode 实际数据库和表名
	 */
	public static void addTableNodes(String logicTable, DataNode actualTableNode) {
		//如果使用多数据源管理ShardingJdbc，例如：jboot.datasource.sd.shardingConfigYaml=sharding-jdbc.yaml
		//则下面应该修改为：ShardingDataSource dataSource = (ShardingDataSource) DbKit.getConfig("sd").getDataSource();
		ShardingDataSource dataSource = (ShardingDataSource) DbKit.getConfig().getDataSource();
		TableRule tableRule = dataSource.getRuntimeContext().getRule().getTableRule(logicTable);
		Collection<String> ds = tableRule.getActualDatasourceNames();
		ds.add(actualTableNode.getDataSourceName());
		List<DataNode> nodeList = tableRule.getActualDataNodes();
		nodeList.add(actualTableNode);
		List<String> actualDataNodes = ListUtils.newArrayList();
		for (DataNode dataNode : nodeList) {
			actualDataNodes.add(dataNode.getDataSourceName() + "." + dataNode.getTableName());
		}
		ReflectUtil.invokeMethod(tableRule, method -> "generateDataNodes".equals(method.getName())
						&& method.getParameterTypes()[0] == List.class && method.getParameterTypes()[1] == Collection.class
				, actualDataNodes, ds);
		Set<String> actualTables = ReflectUtil.getFieldValue(tableRule, "actualTables");
		actualTables.add(actualTableNode.getTableName());
	}
}
